----------------------------------------------------------
-- 道具使用
----------------------------------------------------------

local Lang = require("common.Lang")
local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local Grid = require("bag.Grid")
local ItemDefine = require("bag.ItemDefine")
local BagLogic = require("bag.BagLogic")
local BoxLogic = require("bag.BoxLogic")
local Broadcast = require("broadcast.Broadcast")
local FundLogic = require("present.FundLogic")
local SuperFundLogic = require("present.SuperFundLogic")
local TopupLogic = require("topup.TopupLogic")
local VipLogic = require("vip.VipLogic")
local RoleHeadLogic = require("role.RoleHeadLogic")
local BarTaskLogic = require("bar.BarTaskLogic")
local YjTreasureLogic = require("yjTreasure.YjTreasureLogic")
local ItemComonBuyExcel = require("excel.item").commonBuy
local UnionLogic = require("union.UnionLogic")
local RoleDBLogic = require("role.RoleDBLogic")
local EquipLogic = require("equip.EquipLogic")
local FuwenGrid = require("fuwen.FuwenGrid")
local Util = require("common.Util")
local XingYaoGongMing = require("xingYaoMen.XingYaoGongMing")
local DropExchangeLogic = require("absAct.DropExchangeLogic")
local HeroGrowUp = require("absAct.HeroGrowUp")
local BuyExcel = require("excel.buy")
local LostTempleLogic = require("lostTemple.lostTempleLogic")

cmd 		= {}

FUWEN_BAG_TYPE = 1
NORMAL_BAG_TYPE = 2
EQUIP_BAG_TYPE = 3

-- 所使用道具的相关信息
local function createData(id, cnt, itemConfig, logType, isAuto)
	local data = {}
	data.id = id  					-- 道具id
	data.cnt = cnt 					-- 使用道具数量
	data.left = cnt 				-- 剩余要使用的数量
	data.config = itemConfig 		-- 道具配置
	data.logType = logType 			-- 日志类型
	data.isAuto = isAuto 			-- 是否自动使用
	return data
end

-- 金币
function cmd.jinbi(data, human, value)
	if data.left < 1 then return end
	local sumJinbi = value * data.left
	data.left = 0
	ObjHuman.updateJinbi(human, sumJinbi, data.logType)	
end

-- 钻石
function cmd.zuanshi(data, human, value)
	if data.left < 1 then return end
	local sumZuanshi = value * data.left
	data.left = 0		
	ObjHuman.addZuanshi(human, sumZuanshi, data.logType)
end


-- 经验
function cmd.exp(data, human, value)
	if data.left < 1 then return end
	local sumExp = value * data.left
	data.left = 0
	ObjHuman.addExp(human, sumExp)
end

-- 自选宝箱
function cmd.box(data, human, list)
	BoxLogic.sendBoxList(human, list)	
end

-- 随机宝箱
function cmd.boxRand(data, human, list)
	if data.left < 1 then return end	

	local itemLen = list and #list or 0
    if itemLen < 1 then
		return Broadcast.sendErr(human, Lang.ITEM_USE_ERR_CONFIG)
	end	

	local weightSum = 0
	for i = 1, itemLen do
		local weight = list[i][3]
		weightSum = weightSum + weight
	end
	if weightSum < 1 then
		return Broadcast.sendErr(human, Lang.ITEM_USE_ERR_CONFIG)
	end

    -- 检测数量
    local equipCnt = 0
    local fuWenCnt = 0
	BagLogic.cleanMomentItemList()
    local mathRandom = math.random
	for i = 1, data.left do
		local r = mathRandom(1, weightSum)
		for j = 1, itemLen do
			local itemID = list[j][1]
			local itemCnt = list[j][2]
			local weight = list[j][3]
            local quality = list[j][4]
			if r <= weight then
				BagLogic.updateMomentItem(BagLogic.ADDITEM_TYPE_1, itemID, itemCnt, quality)
                -- 计算装备数量
                if ItemDefine.isEquip(itemID) then
                   equipCnt = equipCnt + itemCnt
                end
                
                if ItemDefine.isFuwen(itemID) then
                   fuWenCnt = fuWenCnt + itemCnt
                end
				break
			end
			r = r - weight
		end		
	end

    -- 检测装备背包空间
    if not EquipLogic.checkEmptyCnt(human, equipCnt) then
       BagLogic.cleanMomentItemList()
       return
    end

    if not FuwenGrid.checkEmptyCnt(human, fuWenCnt) then
       BagLogic.cleanMomentItemList()
       return
    end

	data.left = 0
	BagLogic.addMomentItemList(human, "useBox")
end

-- 固定箱子
function cmd.boxAll(data, human, list)
	if data.left < 1 then return end	

	local cnt = data.left
    local oustList = {}
    local len = 0
    local equipCnt = 0
    local fuWenCnt = 0
	for i = 1, #list do
		local itemID = list[i][1]
		local itemCnt = list[i][2] * cnt
        local quality = list[i][3]
        
        oustList[i] = {}
        oustList[i][1] = itemID
        oustList[i][2] = itemCnt
        oustList[i][3] = quality
        
        -- 计算装备数量
        if ItemDefine.isEquip(itemID) then
           equipCnt = equipCnt + itemCnt
        end

        if ItemDefine.isFuwen(itemID) then
           fuWenCnt = fuWenCnt + itemCnt
        end
	end

    -- 检测装备背包空间
    if not EquipLogic.checkEmptyCnt(human, equipCnt) then
       return
    end

    if not FuwenGrid.checkEmptyCnt(human, fuWenCnt) then
       return
    end

    data.left = 0
    BagLogic.addItemList(human, oustList, "useBox")
end

-- 获得称号
function cmd.chenghao(data, human)
	RoleHeadLogic.active(human, RoleHeadLogic.HEAD_TYPE_4, data.config.icon)
	return true
end

-- 头像
function cmd.head(data, human)
	RoleHeadLogic.active(human, RoleHeadLogic.HEAD_TYPE_1, data.config.icon)
	return true
end

-- 头像框
function cmd.headFrame(data, human)
    RoleHeadLogic.active(human, RoleHeadLogic.HEAD_TYPE_2, data.config.icon)
	return true
end

-- 小基金/大基金
function cmd.superfund(data, human, ftype)
	SuperFundLogic.buySuperFund(human, ftype)
	return true
end

-- 钻石基金
function cmd.fundbuy(data, human, ftype)
    FundLogic.fundBuy(human, ftype)
	return true
end

-- 扫荡特权 
function cmd.tequanmopup(data, human, day)
	local time = os.time()
	if human.db.tequanMopup and human.db.tequanMopup > time then
		time = human.db.tequanMopup
	end
	human.db.tequanMopup = time + day * 86400
	return true
end

-- 民生/悬赏高级特权 
function cmd.tequanbar1(data, human)
	BarTaskLogic.activateBarVip(human, 1)
	return true
end

-- 民生/悬赏豪华特权
function cmd.tequanbar2(data, human)
	BarTaskLogic.activateBarVip(human, 2)
	return true
end

-- 模拟充值
function cmd.chargemoney(data, human, value, noAddYb)
	if data.left < 1 then return end
	local price = value * data.left
	data.left = 0
	TopupLogic.clacTopupAcount(human, price)
    if noAddYb ~= 1 then
    	VipLogic.addExp(human, price*10)
    	ObjHuman.addZuanshi(human, price*10, data.logType)
    end
end

-- 大月卡
function cmd.fundbig(data, human)
	
	return true
end

-- 小月卡
function cmd.fundsmall(data, human)
	
	return true
end

-- 友情值
function cmd.friendheart(data, human, value)
	if data.left < 1 then return end
	local sum = data.left * value
	data.left = 0
	ObjHuman.updateFriendHeart(human, sum, data.logType)
end

-- vip经验
function cmd.vipexp(data, human, value)
	if data.left < 1 then return end
	local sum = data.left * value
	data.left = 0
	VipLogic.addExp(human, sum)
end

--民生任务 情报值
function cmd.qingbao(data, human, value)
	if data.left < 1 then return end
	local sum = value * data.left
	data.left = 0

	BarTaskLogic.addBarQingBao(human,sum)
end

--遗迹探宝
function cmd.yjtreasureYJ(data, human, yaojiType)
	YjTreasureLogic.yjYaoJiAdd(human,data.left,yaojiType)
end

--遗迹探宝
function cmd.heroGrowUp(data, human)
	HeroGrowUp.addJifen(human, data.cnt)
end

function cmd.guildexp(data, human, value)
	if data.left < 1 then return end
	local sum = value * data.left
	data.left = 0
	UnionLogic.addUnionExpByItem(human, sum)
end

function cmd.absDrop(data, human, value)
	if data.left < 1 then return end
	local sum = data.left * value
	data.left = 0
	DropExchangeLogic.addJifen(human, sum)
end

function cmd.zhigou(data, human, value)
    if data.left < 1 then return end
    local buyConf = BuyExcel.buy[value]
    if not buyConf then
        return
    end

    local msg = {}
    msg.logintype = 2
    msg.openid = "oCD-L5RxAtfRe8-aiezdY-Ccla5U"
    msg.openkey = "VsBJf2DKah7QhzU5xuzLNA=="
    msg.yuanbao = buyConf.CN * 10
    msg.buyID = value
    msg.account = human.db.account
    msg.transaction_id = "transaction_id1"
    msg.pf = "android"
    msg.money = buyConf.CN

    require("platform.ApiLogic").CHARGE_CODE_HIS = {}
    require("AdminLogic").adminFunction.tencentPay(msg)
end

function cmd.lostRevice(data, human, value)
   if data.left < 1 then return end

   LostTempleLogic.lostTempleRevice(human)

   return true
end
-----------------------------------------------------------------------------

-- 仅使用道具，不扣道具
function onlyuse(human, id, cnt, logType, isAuto)
	if cnt < 1 then return end

	local itemConfig = ItemDefine.getConfig(id)
	if not itemConfig or not itemConfig.cmd then
		return Broadcast.sendErr(human, Lang.ITEM_USE_ERR_CANT_USE)
	end

	local command = itemConfig.cmd
	local cmdName = command[1]
	if not cmdName or not cmd[cmdName] then
		return Broadcast.sendErr(human, Lang.ITEM_USE_ERR_CANT_USE)
	end

	local data = createData(id, cnt, itemConfig, logType, isAuto)
	while 0 < data.left do
		local isok = cmd[cmdName](data, human, command[2], command[3], command[4])
		if isok then
			data.left = data.left - 1
		else
			break
		end
	end
	return true, data.left
end

-- 使用并扣道具
function use(human, id, cnt)
	if cnt < 1 then return end
	if id < 1 then return end

	local bagCnt = BagLogic.getItemCnt(human, id, true)
	if bagCnt < cnt then
		return Broadcast.sendErr(human, Lang.ITEM_USE_ERR_NO)
	end

	local success, left = onlyuse(human, id, cnt, "item_use")
	if not success then
		return
	end

	local delCnt = cnt - left
	if delCnt > 0 then
		BagLogic.delItem(human, id, delCnt, "item_use")
	end
end

-- 
function sendItemUse(human, id)
	local msgRet = Msg.gc.GC_ITEM_USE
	msgRet.id = id
	Msg.send(msgRet, human.fd)
end

-- 根据id获取item
function sendItemDateByID(human,type,index,id,uuid)
    local msgRet = Msg.gc.GC_ITEM_GET_BY_ID
    if type == FUWEN_BAG_TYPE then
        -- 取出背包
        local bagFileds = {fuwenBag = 1}
        local db = nil
        
        -- 玩家在线直接取缓存
        local tempHuman = ObjHuman.onlineUuid[uuid]
        if tempHuman == nil then
            db = RoleDBLogic.getDb(uuid,bagFileds)
        else
            db = tempHuman.db
        end

        -- 玩家不存在，返回
        if db == nil then
            return
        end

        local fuwenGrid = db.fuwenBag[index]
        -- 符文背包id对不上，返回
        if fuwenGrid == nil or fuwenGrid.id ~= id then
            return
        end
        Grid.makeItem(msgRet.item,id,1,nil,fuwenGrid,index,0)
    elseif type == NORMAL_BAG_TYPE then
        Grid.makeItem(msgRet.item,id,1)
    elseif type == EQUIP_BAG_TYPE then
        -- 取出背包
        local bagFileds = {equipBag = 1}
        local db = nil
        
        -- 玩家在线直接取缓存
        local tempHuman = ObjHuman.onlineUuid[uuid]
        if tempHuman == nil then
            db = RoleDBLogic.getDb(uuid,bagFileds)
        else
            db = tempHuman.db
        end

        -- 玩家不存在，返回
        if db == nil then
            return
        end

        local equipGrid = db.equipBag[index]
        -- 符文背包id对不上，返回
        if equipGrid == nil or equipGrid.id ~= id then
            return
        end
        Grid.makeItem(msgRet.item,id,1,nil,equipGrid,index,0)
    end

    Msg.send(msgRet,human.fd)
end


-- 根据id获取item
function sendItemData(human,itemID)
    local msgRet = Msg.gc.GC_ITEM_GET_BY_ITEM_ID
    local itemCnt = BagLogic.getItemCnt(human,itemID)
    Grid.makeItem(msgRet.item,itemID,itemCnt)
    Msg.send(msgRet,human.fd)
end

function itemBuyQuery(human,itemID)
    local config = ItemComonBuyExcel[itemID]
    if config == nil then
        return
    end
    local msgRet = Msg.gc.GC_ITEM_BUY_QUERY
    Grid.makeItem(msgRet.need,config.price[1],config.price[2])
    Grid.makeItem(msgRet.get,itemID,config.cnt)
    Msg.send(msgRet,human.fd)
end

function itemBuyDo(human,itemID,itemCnt)
    local msgRet = Msg.gc.GC_ITEM_BUY_DO
    msgRet.ret = 0
    local config = ItemComonBuyExcel[itemID]
    if config == nil then
        Msg.send(msgRet,human.fd)
        return
    end

    local needID = config.price[1]
    local needCnt = config.price[2] * itemCnt

    local costCnt = BagLogic.getItemCnt(human,needID)
    if costCnt < needCnt then
        Msg.send(msgRet,human.fd)
        return
    end

	BagLogic.delItem(human, needID, needCnt, "buy_item")
	BagLogic.cleanMomentItemList()
	BagLogic.updateMomentItem(1, itemID, itemCnt*config.cnt)
	BagLogic.addMomentItemList(human, "buy_item")
    msgRet.ret = 1
    Msg.send(msgRet,human.fd)
end

